package com.example.shop_2304.fg

import android.content.Context
import android.os.Bundle
import android.os.Handler
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.Roll
import com.example.base.mvvm.BaseFragment
import com.example.shop_2304.R
import com.example.shop_2304.adapter.CouponAdapter
import com.example.shop_2304.adapter.GoodsAdapter
import com.example.shop_2304.adapter.MenuAdapter
import com.example.shop_2304.adapter.NewsAdapter
import com.example.shop_2304.adapter.TypeAdapter
import com.example.shop_2304.databinding.FragmentHomeBinding
import com.example.shop_2304.utils.GlideUtils
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import java.util.Timer
import java.util.TimerTask


class HomeFragment : BaseFragment<FragmentHomeBinding,HomeViewModel>() {
    val imgs = mutableListOf<String>()//存放轮播图图片地址
    lateinit var menuAdapter: MenuAdapter
    lateinit var newsAdapter: NewsAdapter
    lateinit var typeAdapter: TypeAdapter
    lateinit var timer:Timer
    val handler = Handler()
    var index = 0//当前显示的新闻的小标
    lateinit var goodsAdapter: GoodsAdapter
    var type = 4//分类  默认为4，因为它在第一个
    var page = 1//页码
    val limit = 5//建议不要给10 ，因为串中的数据太少了，要不然分页看不出来
    //优惠券
    lateinit var couponAdapter: CouponAdapter
    override fun initView() {
        //请求数据
        viewModel.index()
        //初始化菜单
       menuAdapter = MenuAdapter()
       binding.rvMenu.adapter = menuAdapter
       binding.rvMenu.layoutManager = GridLayoutManager(context,5)
        //初始化新闻
        newsAdapter = NewsAdapter()
        binding.rvNews.adapter = newsAdapter
        binding.rvNews.layoutManager = LinearLayoutManager(context)
        //初始化分类
        typeAdapter = TypeAdapter()
        binding.rvType.adapter = typeAdapter
        binding.rvType.layoutManager = GridLayoutManager(context,4)
        //让新闻的数据可以自动滚动  ---使用定时任务
        timer = Timer()
        timer.schedule(object:TimerTask(){
            override fun run() {
                handler.post {
                    binding.rvNews.scrollToPosition(index)//让rv显示指定小标的那行数据
                    index++//下标自增
                    if(index==newsAdapter.data.size){
                        index=0
                    }
                }
            }
        },0,2000)
        //初始化商品
        goodsAdapter = GoodsAdapter()
        binding.rvGoods.adapter = goodsAdapter
        binding.rvGoods.layoutManager = GridLayoutManager(context,2)
        //请求商品数据
        viewModel.indexGoods(type, limit, page)
        //点击分类，下方商品数据可以变化
        typeAdapter.setOnItemClickListener { adapter, view, position ->
            //当点击分类时，全局变量 type发生变化   page = 1
            type = typeAdapter.data[position].type.toInt()
            page = 1
            typeAdapter.setType(type)
            viewModel.indexGoods(type, limit, page)
        }
        //刷新加载更多
        binding.smart.setOnRefreshLoadMoreListener(object :OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                viewModel.indexGoods(type, limit, page)
                binding.smart.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                viewModel.indexGoods(type, limit, page)
                binding.smart.finishLoadMore()
            }
        })
        //初始化优惠券
        couponAdapter = CouponAdapter()
        binding.rvCoupon.adapter=couponAdapter
        binding.rvCoupon.layoutManager = LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false)
        //请求优惠券
        viewModel.coupon("10","1","1")
        //点击优惠券进行领取
        couponAdapter.setOnItemClickListener { adapter, view, position ->
            if(couponAdapter.data[position].isUse){
                ToastUtils.showLong("已经领取过了，不能重复领取")
            }else{
                viewModel.couponReceive(couponAdapter.data[position].id)
                //直接修改对应文字
                couponAdapter.data[position].isUse = true
                (couponAdapter.getViewByPosition(position,R.id.coupon_tv) as TextView).text = "已领取"

            }
        }
        //点击搜索框，跳转到搜索界面
        binding.clSearch.setOnClickListener {
            ARouter.getInstance().build("/app/SearchActivity").navigation()
        }
        //点击商品item,实现跳转到详情界面
        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/app/XqActivity").withInt("gid",goodsAdapter.data[position].id).navigation()
        }
    }

    override fun initData() {
        //观察数据
        viewModel.indexSuccess.observe(this){
            if(it.code==200){
                //轮播图
                it.data.banner.forEach {
                    imgs.add(it.pic)
                }
                binding.banner.setImages(imgs)
                    .setImageLoader(object:ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            GlideUtils.loadImage(context!!,path.toString(),imageView!!)
                        }
                    })
                    .setDelayTime(2000)//轮播时长
                    .setBannerStyle(BannerConfig.NUM_INDICATOR)
                    .setOnBannerListener {
                        ToastUtils.showLong("点击的是第$it 张图片")
                    }
                    .start()
                //显示菜单
                menuAdapter.data.clear()
                menuAdapter.data.addAll(it.data.menus)
                menuAdapter.notifyDataSetChanged()
                //展示新闻
                newsAdapter.data.clear()
                newsAdapter.data.addAll(it.data.roll)//目前只有一条
                newsAdapter.data.add(Roll(1,"双11预售","",""))
                newsAdapter.notifyDataSetChanged()
                //展示分类
                typeAdapter.data.clear()
                typeAdapter.data.addAll(it.data.explosiveMoney)
                typeAdapter.notifyDataSetChanged()

            }else{
                ToastUtils.showLong(it.message)
            }
        }
        //观察商品数据
        viewModel.goodsSuccess.observe(this){
            if(it.code==200){
                //当page为1时，可能是初始化状态，或者是刷新的状态，都需要将数据清空再添加
                if(page==1){
                    goodsAdapter.data.clear()
                }
                goodsAdapter.data.addAll(it.data.list)
                goodsAdapter.notifyDataSetChanged()
                //当请求不出新的数据时，可以给出友好提示
                if(it.data.list.size==0){
                    ToastUtils.showLong("我也是有底线的")
                }
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.couponSuccess.observe(this){
            if(it.code==200){
                couponAdapter.data.clear()
                couponAdapter.data.addAll(it.data)
                couponAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.receiveSuccess.observe(this){
            ToastUtils.showLong(it.message)

        }


    }

    override fun getLayout(): Int  = R.layout.fragment_home

    override fun getViewModel(): Class<HomeViewModel>  = HomeViewModel::class.java

}